<template>
  <div>
    <MyComponent>
      <template #content>
        <div class="category-manager">
          <el-row>
            <el-col :span="24">
              <el-button type="primary" @click="addCategoryDialog = true">添加分类</el-button>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-table :data="categories" style="width: 100%">
                <el-table-column prop="name" label="分类名称" width="180"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                        size="mini"
                        @click="editCategory(scope.row.id, scope.row.name)">编辑</el-button>
                    <el-button
                        size="mini"
                        type="danger"
                        @click="deleteCategory(scope.row.id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>

          <!-- 添加分类对话框 -->
          <el-dialog
              title="添加分类"
              :visible.sync="addCategoryDialog"
              width="30%"
              :before-close="handleClose">
            <el-form ref="addCategoryForm" :model="addCategoryForm" label-width="80px">
              <el-form-item label="分类名称">
                <el-input v-model="addCategoryForm.name" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addCategoryDialog = false">取 消</el-button>
              <el-button type="primary" @click="addCategory">确 定</el-button>
            </span>
          </el-dialog>

          <!-- 编辑分类对话框 -->
          <el-dialog
              title="编辑分类"
              :visible.sync="editCategoryDialog"
              width="30%"
              :before-close="handleCloseEdit">
            <el-form ref="editCategoryForm" :model="editCategoryData" label-width="80px">
              <el-form-item label="分类名称">
                <el-input v-model="editCategoryData.name" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="editCategoryDialog = false">取 消</el-button>
              <el-button type="primary" @click="updateCategory">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </template>
    </MyComponent>
  </div>
</template>

<script>
import MyComponent from '@/components/backend.vue';
import axios from '@/request/request';

export default {
  components: {
    MyComponent,
  },
  data() {
    return {
      addCategoryForm: {
        name: ''
      },
      categories: [], // 存储分类数据
      newCategoryName: '', // 新分类的名称
      addCategoryDialog: false, // 添加分类对话框的状态
      editCategoryDialog: false, // 编辑分类对话框的状态
      editCategoryData: { id: '', name: '' }, // 存储要编辑的分类数据
    };
  },
  methods: {
    getCategory() {
      axios.get('/api/categories')
          .then(response => {
            this.categories = response.data;
          })
          .catch(error => {
            console.error('Error:', error);
          });
    },
    addCategory() {
      if (this.addCategoryForm.name.trim() !== '') {
        this.newCategoryName = this.addCategoryForm.name; // 确保变量名一致
        axios.post('/api/categories', {
          name: this.newCategoryName
        })
            .then(response => {
              this.getCategory(); // 更新分类列表
              this.addCategoryForm.name = ''; // 清空输入框
              this.addCategoryDialog = false; // 关闭对话框
            })
            .catch(error => {
              console.error('Error:', error);
            });
      }
    },
    editCategory(categoryId, currentName) {
      this.editCategoryData.id = categoryId;
      this.editCategoryData.name = currentName;
      this.editCategoryDialog = true;
    },
    updateCategory() {
      axios.put(`/api/categories/${this.editCategoryData.id}`, { name: this.editCategoryData.name })
          .then(response => {
            this.getCategory();
            this.editCategoryDialog = false;
          })
          .catch(error => {
            console.error('Error updating category:', error);
          });
    },
    deleteCategory(categoryId) {
      axios.delete(`/api/categories/${categoryId}`)
          .then(response => {
            console.log('Category deleted:', response);
            this.getCategory();
          })
          .catch(error => {
            if (error.response && error.response.status === 500) {
              // 服务器返回了500错误，输出特定消息
              this.$message.error('该分类被使用暂时不能删除');
            } else {
              // 其他错误
              console.error('Error deleting category:', error);
            }
          });
    },
    handleClose() {
      this.addCategoryDialog = false;
    },
    handleCloseEdit() {
      this.editCategoryDialog = false;
    }
  },
  mounted() {
    this.getCategory();
  }
};
</script>

<style scoped>
.category-manager {
  padding: 20px;
}
</style>